package com.amap.template;

import com.alibaba.fastjson2.JSONObject;
import com.amap.builder.AmapParamBuilder;
import com.amap.config.AmapMerchantConfig;
import com.amap.constants.Constants;
import com.amap.exception.AmapException;
import com.amap.http.HttpClientStrategy;
import com.amap.sign.SignStrategy;
import java.util.Map;
/**
 * @author liuyi
 * @since 2025/10/31 11:17
 */

public class AmapClientTemplate {
    private final AmapMerchantConfig config;
    private final SignStrategy signStrategy;
    private final HttpClientStrategy httpClient;

    public JSONObject execute(AmapParamBuilder paramBuilder) throws AmapException {
        Map<String, String> params = paramBuilder.build(this.config);
        String sign = this.signStrategy.generateSign(params, this.config.getMerchantPrivateKey());
        params.put(Constants.PARAM_SIGN, sign);
        params.put(Constants.PARAM_SIGN_TYPE, this.config.getSignType());
        String responseBody = this.httpClient.postForm(this.config.getServerUrl(), params);
        if (responseBody != null && !responseBody.isEmpty()) {
            return JSONObject.parseObject(responseBody);
        } else {
            throw new RuntimeException("高德接口返回空响应");
        }
    }

    public AmapClientTemplate(AmapMerchantConfig config, SignStrategy signStrategy, HttpClientStrategy httpClient) {
        this.config = config;
        this.signStrategy = signStrategy;
        this.httpClient = httpClient;
    }
}
